<Switch>
该组件主要用来做唯一匹配。
<Router>
<div>
<Link to="/" children="home" />
<Link to="/about" children="about" />
<Route path="/" render={(props)=>{return <h1>home</h1>}}
<Route path="/about" render={(props)=>{return <h1>about</h1>}}
<Route path="/:path" render={(props)=>{return <h1>{props.match.params.path}</h1>}}
</div>
</Router>
对于这个例子,Route都没有指定exact,访问"/"路由,三个组件都会被渲染。即使都指定了exact,访问"/",第三个路由也是匹配的。
对于Route,执行的是全部匹配,设计如此。但如果我想匹配到某一个就不再继续匹配了,就需要用到Switch。
<Router>
<div>
<Link to="/" children="home" />
<Link to="/about" children="about" />
<Switch>
<Route path="/" render={(props)=>{return <h1>home</h1>}}
<Route path="/about" render={(props)=>{return <h1>about</h1>}}
<Route path="/:path" render={(props)=>{return <h1>{props.match.params.path}</h1>}}
</Switch>
</div>
</Router>
本例中,当第一个路由匹配成功后,就不再匹配后续路由了。访问"/",只有第一个路由组件会被渲染。
基本属性:
location:object
用法与之前的一致。
<Router>
<div>
<Link to="/" children="home" />
<Link to="/about" children="about" />
<Switch location={{pathname:"/"}}>
<Route exact path="/" render={(props)=>{return <h1>home</h1>}}
<Route exact path="/about" render={(props)=>{return <h1>about</h1>}}
<Route exact path="/:path" render={(props)=>{return <h1>{props.match.params.path}</h1>}}
</Switch>
</div>
</Router>
本例中,手动指定了location的pathname,所以即使页面路由发生变化,匹配的路由依然是"/",渲染"/"路由组件。